<template>
    <div style="display: flex;">
        <el-form :model="data.form" ref="formRef" :rules="data.rules" label-width="150px" style="width: 45%; flex: 1;">
            <div style="text-align: center;">
                <h2 style="color: #606266;">企业信息</h2>
            </div>
            <el-form-item label="企业编号">
                <label v-if="!data.isedit">{{ data.form.enterpriseId }}</label>
                <el-input v-else v-model="data.form.enterpriseId" disabled></el-input>
            </el-form-item>
            <el-form-item label="企业名称 " prop="enterpriseName">
                <label v-if="!data.isedit">{{ data.form.enterpriseName }}</label>
                <el-input v-else v-model="data.form.enterpriseName"></el-input>
            </el-form-item>
            <el-form-item label="企业地址 " prop="enterpriseAddress">
                <label v-if="!data.isedit">{{ data.form.enterpriseAddress }}</label>
                <el-input v-else v-model="data.form.enterpriseAddress"></el-input>
            </el-form-item>
            <el-form-item label="统一社会信用代码 ">
                <label v-if="!data.isedit">{{ data.form.taxNumber }}</label>
                <el-input v-else v-model="data.form.taxNumber" disabled></el-input>
            </el-form-item>
            <el-form-item label="法定代表人姓名 " prop="bossName">
                <label v-if="!data.isedit">{{ data.form.bossName }}</label>
                <el-input v-else v-model="data.form.bossName"></el-input>
            </el-form-item>
            <el-form-item label="法定代表人身份证号 " prop="idNumber">
                <label v-if="!data.isedit">{{ data.form.idNumber }}</label>
                <el-input v-else v-model="data.form.idNumber"></el-input>
            </el-form-item>
            <el-form-item label="法定代表人手机号 " prop="phone">
                <label v-if="!data.isedit">{{ data.form.phone }}</label>
                <el-input v-else v-model="data.form.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="账号 " prop="username">
                <label v-if="!data.isedit">{{ data.form.username }}</label>
                <el-input v-else v-model="data.form.username"></el-input>
            </el-form-item>
            <el-form-item label="登录密码 " prop="password">
                <label v-if="!data.isedit">{{ data.form.password }}</label>
                <el-input v-else v-model="data.form.password" type="password" show-password></el-input>
            </el-form-item>
            <div style="text-align: center; margin-top: 20px;">
                <el-button class="updateButton" v-if="!data.isedit" type="primary"
                    @click="data.isedit = true">修改</el-button>
                <div v-else>
                    <el-button class="updateButton" type="primary" @click="handleConfirm">保存</el-button>
                    <el-button class="cancelButton" type="primary" @click="handleCancel">取消</el-button>
                </div>
            </div>
        </el-form>
        <div style="flex: 1;">
            <!-- 年份选择器，绑定到 selectedYear -->
            <el-select v-model="selectedYear" placeholder="请选择年份" @change="handleYearChange" class="year-select">
                <el-option v-for="year in availableYears" :key="year" :label="year" :value="year" />
            </el-select>
            <Chart :option="lineOption" width="100%" height="400px" theme="light" :autoresize="true"
                :loading="loading" />
        </div>
    </div>
</template>
<script setup>
import request from '@/utils/request';
import { onMounted, reactive, ref, watch } from 'vue';
import { Edit, Delete } from '@element-plus/icons-vue';
import router from '@/router';
import Chart from '@/components/Chart.vue'

const data = reactive({
    form: JSON.parse(localStorage.getItem('enterprise')),
    enterprise: {
        enterpriseId: JSON.parse(localStorage.getItem('enterprise')).enterpriseId,
        enterpriseAddress: '',
        bossName: '',
        phone: '',
        idNumber: '',
        taxNumber: '',
        enterpriseName: '',
        username: '',
        password: '',
    },
    isedit: false,////是否为修改，true为修改，false为查看
    rules: {
        enterpriseName: [
            { required: true, message: '请输入企业名称', trigger: ['change', 'blur'] },
            { max: 20, message: '企业名称长度在20个字符以内', trigger: ['change', 'blur'] }
        ],
        enterpriseAddress: [
            { required: true, message: '请输入企业地址', trigger: ['change', 'blur'] },
            { max: 50, message: '企业地址长度在50个字符以内', trigger: ['change', 'blur'] }
        ],
        bossName: [
            { required: true, message: '请输入法定代表人姓名', trigger: ['change', 'blur'] },
            { min: 2, max: 10, message: '法定代表人姓名长度在2到10个字符之间', trigger: ['change', 'blur'] }
        ],
        idNumber: [
            { required: true, message: '请输入法定代表人身份证号', trigger: ['change', 'blur'] },
            { pattern: /^[0-9]{17}[0-9X]$/, message: '法定代表人身份证号必须为18位数字或字母X', trigger: ['change', 'blur'] }
        ],
        phone: [
            { required: true, message: '请输入法定代表人手机号', trigger: ['change', 'blur'] },
            { pattern: /^1[3-9]\d{9}$/, message: '法定代表人手机号格式不正确', trigger: ['change', 'blur'] }
        ],
        username: [
            { required: true, message: '请输入账号', trigger: ['change', 'blur'] },
            { pattern: /^[A-Za-z0-9]{6,10}$/, message: '请输入有效的账号', trigger: ['change', 'blur'] }
        ],
        password: [
            { required: true, message: '请输入密码', trigger: ['change', 'blur'] },
            { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d.@]{6,20}$/, message: '密码必须为6-20位，包含大小写字母和数字，可以包含.和@', trigger: ['change', 'blur'] }
        ],
    }
})
const formRef = ref()

const emit = defineEmits(['updateEnterprise']);
const handleConfirm = () => {//修改或查看企业信息
    formRef.value.validate((valid) => {
        if (valid) {
            request.post('/enterprise/update', data.form).then(res => {
                if (res.code === '200') {
                    ElMessage.success('修改成功')
                    const updatedEnterprise = res.data;
                    console.log("res.data" + updatedEnterprise)
                    const currentEnterprise = JSON.parse(localStorage.getItem('enterprise'));
                    // 合并更新后的企业信息
                    const mergedEnterprise = { ...currentEnterprise, ...updatedEnterprise };
                    localStorage.setItem('enterprise', JSON.stringify(mergedEnterprise));
                    Object.assign(data.form, mergedEnterprise); // 更新表单数据
                    data.isedit = false
                    window.location.reload();//刷新页面
                }
                else {
                    ElMessage.error(res.message)
                }
            })
        } else {
            ElMessage.error("修改失败，请检查信息是否正确")
            return false;
        }
    })
}

const handleCancel = () => {//取消修改
    data.form = JSON.parse(localStorage.getItem('enterprise'));
    data.isedit = false
}


/****************************柱状图***********************************/
const lineOption = ref({})// 折线图的配置对象
const loading = ref(true)// 控制图表加载状态
const selectedYear = ref(new Date().getFullYear())// 当前选中的年份
// 可选择的年份列表（最近三年）
const availableYears = ref([new Date().getFullYear() - 2, new Date().getFullYear() - 1, new Date().getFullYear()])
const fetchPensionTrend = () => {// 获取养老金趋势数据
    loading.value = true
    request.get('/pension/searchEnterprisePage', {
        params: {
            enterpriseId: data.enterprise.enterpriseId,
        }
    }).then(res => {
        if (res.code === '200') {
            const rawData = res.data.list // 获取原始数据
            // 获取当前年份（如 2025）
            const currentYear = new Date().getFullYear()
            // 过滤数据：根据年份过滤并格式化数据
            const filteredData = rawData.filter(item => {
                const [yyyy, mm] = item.pensionTerm.split('-')
                const fullYear = parseInt(yyyy) // 获取完整的年份
                return fullYear === selectedYear.value
            })
            // 前端聚合：按年份和月份分组并汇总金额
            const grouped = {}
            filteredData.forEach(item => {
                const [yyyy, mm] = item.pensionTerm.split('-') // 提取年份和月份
                const termLabel = `${yyyy}-${mm}` // 转换为 "2025-04"格式
                const money = Number(item.pensionMoney) || 0
                grouped[termLabel] = (grouped[termLabel] || 0) + money
            })
            // 排序并准备图表数据
            const sortedTerms = Object.keys(grouped).sort()
            const totals = sortedTerms.map(term => grouped[term])
            lineOption.value = {
                title: {
                    text: `${selectedYear.value} 企业每月养老保险缴纳趋势图`,
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis'
                },
                xAxis: {
                    type: 'category',
                    data: sortedTerms,
                    boundaryGap: false
                },
                yAxis: {
                    type: 'value',
                    name: '缴纳金额（元）'
                },
                series: [
                    {
                        name: '缴纳金额',
                        type: 'line',
                        data: totals,
                        smooth: true,
                        areaStyle: {
                            color: '#91cc75'
                        }
                    }
                ]
            }
        } else {
            ElMessage.error(res.message || '加载数据失败')
        }
    }).catch(err => {
        console.error('请求失败:', err)
        ElMessage.error('图表数据请求异常')
    }).finally(() => {
        loading.value = false
    })
}
// 监听年份变化，更新图表
const handleYearChange = () => {
    fetchPensionTrend()
}
// 页面加载时请求一次数据
onMounted(fetchPensionTrend)
</script>

<style scoped>
.el-form-item label {
    /* 自定义大小 */
    color: #606266;
}

.updateButton {
    width: 20%;
    height: 5vh;
    font-size: 16px;
    /* 自定义大小 */
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
    border-radius: 5px;
}

.cancelButton {
    width: 20%;
    height: 5vh;
    font-size: 16px;
    /* 自定义大小 */
    color: #000000;
    background-color: #cacfce;
    border-color: #cacfce;
    border-radius: 5px;
}
.year-select {
    width: 200px;
    margin-bottom: 20px;
    margin-left: 20px;
    margin-top: 20px;
    display: inline-block;
}
</style>